import BufferMethod from './BufferMethod';
import CatchMethod from './CatchMethod';

const Get = url => {
  return fetch(url)
    .then(res => res.json())
    .then(data => {
      const { status, message } = data;
      if (status !== 200) {
        return Promise.reject(data);
      }
      return Promise.resolve(message);
    });
};

const Post = (url, ext) => {
  return fetch(url, {
    method: 'POST',
    body: JSON.stringify(ext),
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  })
    .then(res => res.json())
    .then(data => {
      const { status, message } = data;
      if (status !== 200) {
        return Promise.reject(data);
      }
      return Promise.resolve(message);
    });
};

const Put = (url, ext) => {
  return fetch(url, {
    method: 'PUT',
    body: JSON.stringify(ext),
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  })
    .then(res => res.json())
    .then(data => {
      const { status, message } = data;
      if (status !== 200) {
        return Promise.reject(data);
      }
      return Promise.resolve(message);
    });
};

const Delete = url => {
  return fetch(url, {
    method: 'DELETE',
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  })
    .then(res => res.json())
    .then(data => {
      const { status, message } = data;
      if (status !== 200) {
        return Promise.reject(data);
      }
      return Promise.resolve(message);
    });
};

const PostForm = (url, form) => {
  return fetch(url, {
    method: 'POST',
    body: form
  })
    .then(res => res.json())
    .then(data => {
      const { status, message } = data;
      if (status !== 200) {
        return Promise.reject(data);
      }
      return Promise.resolve(message);
    });
};

export default {
  Get: CatchMethod(BufferMethod(Get)),
  Post: CatchMethod(BufferMethod(Post)),
  PostForm: CatchMethod(BufferMethod(PostForm)),
  Put: CatchMethod(BufferMethod(Put)),
  Delete: CatchMethod(BufferMethod(Delete))
};
